<?php

class gettext
{

   private $_translations = array();

   public function  __construct()
   {
      $DB = database::getInstance();
      $DB->sql = 'SELECT * FROM `meccano_translations` ORDER BY `name`, `key`, `value`';
      
      $this->_translations = $this->buildTranslationArray($DB->DB_Fetch());
   }

   /**
    * Class destructor
    */
   public function __destruct()
   {
      if (config::read('cache_system') == 1 && !file_exists(ROOT . CACHE . '/meccano.translations.inc'))
      {
         file_put_contents(ROOT . CACHE . '/meccano.translations.inc', serialize($this));
      }
   }

   public function __sleep()
   {
      return array('_translations');
   }

   public function __get($name)
   {
      $lang = request::getLang('currentId');

      if(property_exists($this->_translations[$lang], $name))
      {
         return $this->_translations[$lang]->{$name};
      }

      return FALSE;
   }

   /**
    * Get full translation array
    * 
    * @return array
    */
   public function _getAll()
   {
      return $this->_translations;
   }

   /**
    * Get translated string
    *
    * @param string $name
    * @param string $key
    * @param integer $lang
    * @return mixed
    */
   public function getTranslation($name, $key = false, $lang = false)
   {
      $lang           = request::getLang('data', $lang);
      $lang           = $lang['id'];
      $default_langid = request::getLang('defaultId');
      
      if(empty($this->_translations[$lang]) || !is_object($this->_translations[$lang])) return '';

      $r = MODE_DEBUG ? '[no_translation -'. $name .($key ? ' -'. $key : '') .']' : FALSE;
      if($name && $key)
      {
         if(is_numeric($key)) $key = '_'. $key;
         if(property_exists($this->_translations[$lang], $name) && property_exists($this->_translations[$lang]->{$name}, $key))
         {
            $r = $this->_translations[$lang]->{$name}->{$key};
         } elseif(property_exists($this->_translations[$default_langid], $name) && property_exists($this->_translations[$default_langid]->{$name}, $key))
         {
            $r = $this->_translations[$default_langid]->{$name}->{$key};
         }
      } elseif($name)
      {
         if(property_exists($this->_translations[$lang], $name))
         {
            $r = $this->_translations[$lang]->{$name};
         } elseif(property_exists($this->_translations[$default_langid], $name))
         {
            $r = $this->_translations[$default_langid]->{$name};
         }
      } else
      {
         return $this->_translations[$lang_id];
      }

      return is_object($r) ? (array)$r : htmlspecialchars($r);
   }

   /**
    * Build array with translated strings
    *
    * @param array $flatArray
    * @return array
    */
   private function buildTranslationArray($flatArray)
   {
      $translation = array();
      for($i=0, $t=sizeof($flatArray); $i<$t; $i++)
      {
         $row = $flatArray[$i];
         $lang_id = $row['lang'];

         if(empty($translation[$lang_id]))
         {
            $translation[$lang_id] = new stdClass();
         }


         if(!empty($row['key']))
         {
            $key = is_numeric(substr($row['key'], 0, 1)) ? '_'. $row['key'] : $row['key'];
            if(!property_exists($translation[$lang_id], $row['name']))
            {
               $translation[$lang_id]->{$row['name']} = new stdClass();
            }

            $translation[$lang_id]->{$row['name']}->{$key} = $row['value'];
         } else
         {
            $translation[$lang_id]->{$row['name']} = $row['value'];
         }
      }

      return $translation;
   }

   /**
    * Get instance of Translation object
    *
    * @staticvar Fields $object_store_singelton
    * @param integer $node
    * @return Fields
    */
   static public function getInstance()
   {
      static $object_store_singelton;
      if (!is_object($object_store_singelton))
      {
         $object_store_singelton = gettext::renewFromCache();
         if (!is_object($object_store_singelton))
         {
            $object_store_singelton = new gettext();
         }
      }
      return $object_store_singelton;
   }


   static public function translate($name = false, $key = false)
   {
      $_this = gettext::getInstance();
      return $_this->getTranslation($name, $key);
   }

   /**
    * Renew Translation object from Cache
    *
    * @return object
    */
   public static function renewFromCache()
   {
      if(config::read('cache_system') == 1 && file_exists(ROOT . CACHE . '/meccano.translations.inc'))
      {
         if ($restored_object = unserialize(file_get_contents(ROOT . CACHE . '/meccano.translations.inc')))
         {
            return $restored_object;
         }
      }

      return FALSE;
   }

   public static function exportCSV()
   {
      $langs  = request::getLang('all');

      $csv = 'KEY (do not edit)';
      foreach($langs AS $l)
      {
         $csv .= ';'. $l['title'] .' ['. $l['iso'] .']';
      }
      $csv .= EOL;

      $_this = gettext::getInstance();
      $translations = $_this->_getAll();

      $tmp = array();
      foreach($translations AS $l=>$tr)
      {
         foreach($tr AS $n=>$v)
         {
            if(is_object($v))
            {
               foreach($v AS $k=>$vv)
               {
                  $tmp[$n .'-'. $k][$l] = $vv;
               }
            } else
            {
               $tmp[$n][$l] = $v;
            }
         }
      }
      $translations = $tmp;
      unset($tmp);

      foreach($translations AS $k=>$v)
      {
         $csv .= $k;
         foreach($langs AS $l)
         {
            $value = isset($v[$l['id']]) ? $v[$l['id']] : '';
            $value = strpos($value, ';') !== FALSE ? '"'. str_replace('"', '\"', $value) .'"' : $value;
            $csv .= ';'. $value;
         }
         $csv .= EOL;
      }
      //var_dump($translations); exit();

      return $csv;
   }
}